<template>
  <div>
    <InfoTable
      title="月账单"
      :data="bills"
      :columns="columns"
      :pagination="pagination"
      key-field="id"
      :show-create-button="false"
      :show-batch-delete-button="false"
      :show-selection="true"
      :selected-items="selectedItems"
      :actions="[{ name: 'export', label: '导出', type: 'edit' }]"
      @action="handleAction"
      @page-change="handlePageChange"
      @toggle-item-selection="toggleItemSelection"
      @toggle-select-all="toggleSelectAll"
      @clear-selection="clearSelection"
    >
      <template #advanced-search>
        <div class="search-filters">
          <div class="filter-group">
            <label>年份：</label>
            <input 
              type="number" 
              v-model="selectedYear" 
              class="year-input"
              placeholder="请输入年份"
              min="2000"
              max="2100"
            />
          </div>
          
          <div class="filter-group">
            <label>月份：</label>
            <input 
              type="number" 
              v-model="selectedMonth" 
              class="month-input"
              placeholder="请输入月份(1-12)"
              min="1"
              max="12"
            />
          </div>
          
          <div class="filter-actions">
            <button @click="handleSearch" class="search-button">搜索</button>
            <button @click="handleReset" class="reset-button">重置</button>
            <button @click="handleExportAll" class="export-all-button">导出全部</button>
            <button 
              @click="handleExportSelected" 
              class="export-selected-button"
              :disabled="selectedItems.length === 0"
            >
              导出选中<span v-if="selectedItems.length > 0"> ({{ selectedItems.length }})</span>
            </button>
          </div>
        </div>
      </template>
      
      <template #column-call_duration="{ item }">
        {{ item.call_duration }}
      </template>
      
      <template #column-total_fee="{ item }">
        {{ (item.total_fee / 100).toFixed(2) }}
      </template>
      
      <template #column-virtual_fee="{ item }">
        {{ (item.virtual_fee / 100).toFixed(2) }}
      </template>
      
      <template #column-create_time="{ item }">
        {{ formatDate(item.create_time) }}
      </template>
    </InfoTable>
  </div>
</template>

<script>
import InfoTable from '@/components/InfoTable.vue'
import { getBillInfo, queryBillsByYearMonth } from '@/apis/billInfo' // 更新导入的接口
import { ElMessage } from 'element-plus'

export default {
  name: 'MonthlyBill',
  components: {
    InfoTable
  },
  data() {
    return {
      bills: [], // 存储当前显示的账单数据
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      columns: [
        { key: 'id', title: '账单ID' },
        { key: 'callerPhone', title: '主叫手机号' },
        { key: 'calleePhone', title: '被叫手机号' },
        { key: 'virtualNumber', title: '虚拟号' },
        { key: 'callDuration', title: '通话时长(秒)' },
        { key: 'totalFee', title: '总费用(元)' },
        { key: 'virtualFee', title: '服务费(元)' },
        { key: 'createTime', title: '生成时间' }
      ],
      loading: false,
      selectedYear: '',
      selectedMonth: '',
      showAllData: true,  // 标识是否显示全部数据
      selectedItems: [] // 存储选中的项目ID
    }
  },
  methods: {
    // 获取账单数据
    async fetchBillData() {
      this.loading = true
      try {
        // 如果有年份或月份筛选条件，且不是显示全部数据的状态，则使用按年月查询接口
        if ((this.selectedYear || this.selectedMonth) && !this.showAllData) {
          // 构造查询参数，只需要年份和月份，不需要分页参数
          const queryParams = {}
          
          if (this.selectedYear) {
            queryParams.year = parseInt(this.selectedYear)
          }
          if (this.selectedMonth) {
            queryParams.month = parseInt(this.selectedMonth)
          }
          
          const res = await queryBillsByYearMonth(queryParams)
          if (res && res.code === 0) {
            // 对于新接口，直接处理返回的数据
            this.bills = Array.isArray(res.data) ? res.data : []
            this.pagination.total = this.bills.length
          } else {
            ElMessage.error(res?.msg || '获取账单数据失败')
            this.bills = []
            this.pagination.total = 0
          }
        } else if (this.showAllData) {
          // 只有在显示全部数据状态时，才获取所有账单数据（仍需要分页）
          const params = {
            pageNo: this.pagination.current,
            pageSize: this.pagination.pageSize
          }
          
          const res = await getBillInfo(params)
          if (res && res.code === 0) {
            const data = res.data || {}
            this.bills = data.list || data.records || []
            this.pagination.total = data.total || 0
            
            // 如果响应数据在顶层，直接使用res.data
            if (this.bills.length === 0 && Array.isArray(res.data) && res.data.length > 0) {
              this.bills = res.data
              this.pagination.total = res.data.length
            }
          } else {
            ElMessage.error(res?.msg || '获取账单数据失败')
            this.bills = []
            this.pagination.total = 0
          }
        }
      } catch (error) {
        console.error('获取账单数据异常:', error)
        ElMessage.error('获取账单数据异常: ' + (error.message || '未知错误'))
        this.bills = []
        this.pagination.total = 0
      } finally {
        this.loading = false
      }
    },
    
    // 切换项目选择状态
    toggleItemSelection(itemId) {
      const index = this.selectedItems.indexOf(itemId);
      if (index > -1) {
        // 如果已选中，则取消选中
        this.selectedItems.splice(index, 1);
      } else {
        // 如果未选中，则添加到选中列表
        this.selectedItems.push(itemId);
      }
    },
    
    // 切换全选状态
    toggleSelectAll() {
      if (this.selectedItems.length === this.bills.length) {
        // 如果已全选，则取消全选
        this.selectedItems = [];
      } else {
        // 如果未全选，则全选当前页的所有项目
        this.selectedItems = this.bills.map(item => item.id);
      }
    },
    
    // 获取所有账单数据
    async fetchAllBills() {
      this.showAllData = true
      await this.fetchBillData()
    },
    
    handleSearch() {
      // 点击搜索按钮后，设置为不显示全部数据
      this.showAllData = false
      // 重置分页到第一页
      this.pagination.current = 1
      // 清空选中项
      this.clearSelection()
      // 获取数据
      this.fetchBillData()
    },
    
    handleReset() {
      // 重置筛选条件
      this.selectedYear = ''
      this.selectedMonth = ''
      // 重置分页到第一页
      this.pagination.current = 1
      // 清空选中项
      this.clearSelection()
      // 获取所有数据
      this.fetchAllBills()
    },
    
    // 导出选中的账单
    handleExportSelected() {
      if (this.selectedItems.length === 0) {
        ElMessage.warning('请先选择要导出的账单')
        return
      }
      
      // 从当前账单数据中筛选出选中的账单
      const selectedBills = this.bills.filter(bill => 
        this.selectedItems.includes(bill.id)
      )
      
      if (selectedBills.length === 0) {
        ElMessage.warning('未找到选中的账单数据')
        return
      }
      
      // 导出选中的账单数据
      const csvContent = this.formatBillsToCSV(selectedBills)
      const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      const dateStr = this.selectedYear ? 
        (this.selectedMonth ? `${this.selectedYear}年${this.selectedMonth}月` : `${this.selectedYear}年`) : 
        '全部'
      link.setAttribute('href', url)
      link.setAttribute('download', `月账单_选中_${dateStr}.csv`)
      link.style.visibility = 'hidden'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      ElMessage.success(`成功导出 ${selectedBills.length} 条账单`)
    },
    
    handleExportAll() {
      if (this.bills.length === 0) {
        ElMessage.warning('没有可导出的数据')
        return
      }
      
      // 导出所有筛选后的账单数据
      const csvContent = this.formatBillsToCSV(this.bills)
      const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      const dateStr = this.selectedYear ? 
        (this.selectedMonth ? `${this.selectedYear}年${this.selectedMonth}月` : `${this.selectedYear}年`) : 
        '全部'
      link.setAttribute('href', url)
      link.setAttribute('download', `月账单_${dateStr}.csv`)
      link.style.visibility = 'hidden'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      ElMessage.success('账单已导出')
    },
    
    handleAction({ action, item }) {
      if (action === 'export') {
        // 导出单个账单
        const csvContent = this.formatBillToCSV(item)
        const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
        const link = document.createElement('a')
        const url = URL.createObjectURL(blob)
        link.setAttribute('href', url)
        link.setAttribute('download', `账单_${item.id}.csv`)
        link.style.visibility = 'hidden'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        
        ElMessage.success(`账单 ${item.id} 已导出`)
      }
    },
    
    handlePageChange(page) {
      this.pagination.current = page
      // 分页时保持当前的查询状态
      this.fetchBillData()
      // 清空选中项
      this.clearSelection()
    },
    
    formatDate(date) {
      // 直接返回数据库中的时间格式，不进行额外转换
      return date || '';
    },
    
    formatBillToCSV(item) {
      // 将单个账单数据格式化为CSV格式
      const headers = [
        '账单ID', '主叫手机号', '被叫手机号', '虚拟号', 
        '通话时长(秒)', '总费用(元)', '服务费(元)', '生成时间'
      ]
      
      const values = [
        item.id,
        item.callerPhone,
        item.calleePhone,
        item.virtualNumber,
        item.callDuration,
        (item.totalFee / 100).toFixed(2),
        (item.virtualFee / 100).toFixed(2),
        this.formatDate(item.create_time)
      ]
      
      return headers.join(',') + '\n' + values.join(',')
    },
    
    formatBillsToCSV(bills) {
      // 将多个账单数据格式化为CSV格式
      const headers = [
        '账单ID', '主叫手机号', '被叫手机号', '虚拟号', 
        '通话时长(秒)', '总费用(元)', '服务费(元)', '生成时间'
      ]
      
      const rows = bills.map(item => [
        item.id,
        item.callerPhone,
        item.calleePhone,
        item.virtualNumber,
        item.callDuration,
        (item.totalFee / 100).toFixed(2),
        (item.virtualFee / 100).toFixed(2),
        this.formatDate(item.create_time)
      ])
      
      const csvContent = [headers.join(',')]
      rows.forEach(row => csvContent.push(row.join(',')))
      
      return csvContent.join('\n')
    },
    // 添加监听数据变化来清空选中项
    clearSelection() {
      this.selectedItems = [];
    }
  },
  
  watch: {
    selectedYear() {
      // 移除自动触发搜索的逻辑
    },
    selectedMonth() {
      // 移除自动触发搜索的逻辑
    }
  }
}
</script>

<style scoped>
.search-filters {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: center;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 15px;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label {
  font-weight: bold;
  white-space: nowrap;
}

.year-input,
.month-input {
  padding: 6px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.year-input,
.month-input {
  width: 80px;
}

.filter-actions {
  display: flex;
  gap: 10px;
  margin-left: auto;
}

.search-button,
.reset-button {
  padding: 8px 16px;
  background-color: #667eea;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.search-button:hover,
.reset-button:hover {
  background-color: #5a6fd8;
}

.export-all-button,
.export-selected-button {
  padding: 8px 16px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.export-all-button:hover,
.export-selected-button:hover {
  background-color: #218838;
}

.export-selected-button:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}
</style>